﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

public class RegisterInfo
{
    /// <summary>
    /// 日志信息字段，描述寄存器的名称和位范围
    /// </summary>
    public string LogInfo { get; set; }

    /// <summary>
    /// 寄存器地址（小端字节序），可以是单个地址或地址范围
    /// </summary>
    public string RegisterAddress { get; set; }

    /// <summary>
    /// 排序地址（用于排序的数值型地址）
    /// </summary>
    public uint SortAddress { get; set; }

    /// <summary>
    /// 参数定义，描述寄存器中的特定位或字段
    /// </summary>
    public string Parameter { get; set; }

    /// <summary>
    /// 参数释义，详细解释该参数的含义和状态
    /// </summary>
    public string Description { get; set; }

    /// <summary>
    /// LogInfo 的首字母大写缩写
    /// </summary>
    public string Abbreviation { get; set; }

    /// <summary>
    /// 备注信息
    /// </summary>
    public string Remark { get; set; }

    public string Category { get; set; } // Boot阶段、出图阶段、Sensor阶段
    public int BitWidth { get; set; } // 位宽，如32位、24位等
    public int RegisterCount { get; set; } // 需要的寄存器数量
    public bool IsArray { get; set; } // 是否为数组
    public int ArraySize { get; set; } // 数组大小
    public int ArrayElementSize { get; set; } // 数组元素大小（寄存器数量）
}


public class RegisterInfoData
{
    private static List<RegisterInfo> _allRegisters;
    private static Dictionary<string, uint> _baseAddresses = new Dictionary<string, uint>();
    // JSON 文件路径（固定在运行目录下）
    private static readonly string JsonFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "registers_config.json");
    /// <summary>
    /// 获取所有寄存器信息（地址为空）
    /// </summary>
    public static List<RegisterInfo> GetRegisterInfos()
    {
        if (_allRegisters != null)
            return _allRegisters;
        // 尝试从JSON文件加载
        try
        {
            if (File.Exists(JsonFilePath))
            {
                _allRegisters = LoadRegistersFromJson(JsonFilePath);
                if (_allRegisters != null && _allRegisters.Count > 0)
                {
                    return _allRegisters;
                }
            }
        }
        catch (Exception ex)
        {
            // JSON加载失败，使用默认生成的数据
            System.Diagnostics.Debug.WriteLine($"从JSON加载寄存器配置失败: {ex.Message}");
        }

        _allRegisters = new List<RegisterInfo>();

        // Boot阶段维测信息
        GenerateBootRegisters();

        // 出图阶段维测信息
        GenerateStreamRegisters();

        // Sensor维测信息
        GenerateSensorRegisters();

        // 主机交互维测信息
        GenerateHostRegisters();

        return _allRegisters;
    }
    /// <summary>
    /// 从JSON文件加载寄存器信息
    /// </summary>
    private static List<RegisterInfo> LoadRegistersFromJson(string filePath)
    {
        try
        {
            if (!File.Exists(filePath))
                return null;

            string jsonString = File.ReadAllText(filePath, Encoding.UTF8);
            var jsonData = JsonConvert.DeserializeObject<RegisterInfoJsonData>(jsonString);

            if (jsonData?.Registers != null)
            {
                return jsonData.Registers;
            }
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine($"反序列化JSON失败: {ex.Message}");
        }

        return null;
    }

    /// <summary>
    /// 保存寄存器信息到JSON文件
    /// </summary>
    public static void SaveRegistersToJson(List<RegisterInfo> registers, string filePath = null)
    {
        try
        {
            string savePath = filePath ?? JsonFilePath;

            var jsonData = new RegisterInfoJsonData
            {
                ExportTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                TotalRegisters = registers.Count,
                Registers = registers
            };

            string jsonString = JsonConvert.SerializeObject(jsonData, Formatting.Indented);
            File.WriteAllText(savePath, jsonString, Encoding.UTF8);
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine($"保存JSON文件失败: {ex.Message}");
            throw new Exception($"保存JSON文件失败: {ex.Message}", ex);
        }
    }

    /// <summary>
    /// 更新寄存器信息并保存到JSON文件
    /// </summary>
    public static void UpdateRegisters(List<RegisterInfo> registers)
    {
        _allRegisters = registers;
        SaveRegistersToJson(registers);
    }


    /// <summary>
    /// 设置基地址并自动计算所有寄存器地址（按实际位宽分配）
    /// </summary>
    /// <param name="baseAddress">起始基地址</param>
    public static void CalculateRegisterAddresses(uint baseAddress)
    {
        var registers = GetRegisterInfos();
        uint currentAddress = baseAddress;

        // 按 LogInfo 分组，每个组分配一个地址
        var groupedRegisters = registers
            .GroupBy(r => r.LogInfo)
            .ToList();

        foreach (var group in groupedRegisters)
        {
            var firstRegister = group.First();
            int byteCount = (firstRegister.BitWidth + 7) / 8;
            if (group.Key == "resetverd1[10]")
            {
                byteCount = 0x28;
            }
            uint endAddress = currentAddress + (uint)byteCount - 1;

            // 设置地址范围
            string addressRange = byteCount > 1 ?
                $"0x{currentAddress:X8}-0x{endAddress:X8}" :
                $"0x{currentAddress:X8}";

            foreach (var register in group)
            {
                register.RegisterAddress = addressRange;
            }

            // 下一个寄存器从当前地址 + 字节数开始
            currentAddress += (uint)byteCount;
        }

        // 地址计算完成后保存到JSON
        SaveRegistersToJson(registers);
    }

    /// <summary>
    /// 生成Boot阶段寄存器信息
    /// </summary>
    private static void GenerateBootRegisters()
    {
        // BootFlag1[31:0]
        AddRegisterGroup("Boot阶段", "BootFlag1[31:0]", 32, new List<(string, string)>
        {
            ("[0]检测Flash内容是否异常", "该bit置1说明Flash内容异常，跳过FlashBoot"),
            ("[1]检测芯片PAD是否开启FlashBoot功能", "该bit置1说明PAD上使能跳过FlashBoot"),
            ("[3]检测Flash设备中是否存在bin文件", "该bit置1说明Flash设备中无Bin文件"),
            ("[4]检测头文件CRC校验结果", "该bit置1说明头文件CRC校验失败"),
            ("[9]检测Patchhead CRC校验结果", "该bit置1说明PatchHead CRC校验失败"),
            ("[10]检测PatchHead中的平台标识", "该bit置1说明PatchHead中的平台标识错误"),
            ("[11]检测PatchHead是否使能", "该bit置1说明PatchHead中的使能位未使能"),
            ("[12]检测Patch Code CRC校验结果", "该bit置1说明Patch Code CRC校验失败"),
            ("[13]检测Patch注册结果", "该bit置1说明Patch注册地址异常，注册失败"),
            ("[16]检测Flash解密结果", "该bit置1说明Flash解密失败"),
            ("[19]检测AppHead CRC校验结果", "该bit置1说明AppHead CRC校验失败"),
            ("[20]检测AppHead中的平台标识", "该bit置1说明AppHead中的平台标识错误"),
            ("[21]检测AppHead是否使能", "该bit置1说明AppHead中的使能位未使能"),
            ("[22]检测App Code数据CRC校验结果", "该bit置1说明App Code数据CRC校验失败"),
            ("[24]检测是否切换分区启动", "该bit置1说明因Flash内容异常，切换分区启动"),
            ("[25]检测是否进行过过FlashBoot重试", "该bit置1说明进入过FlashBoot重试机制")
        });

        // BootFlag2[31:0]
        AddRegisterGroup("Boot阶段", "BootFlag2[31:0]", 32, new List<(string, string)>
        {
            ("[0]检测Boot_config区0区BOOT模式", "该bit置1说明Boot_config区0区BOOT模式错误"),
            ("[1]检测Boot_config区0区PLATFORM_ID", "该bit置1说明Boot_config区0区PLATFORM_ID错误"),
            ("[2]检测Boot_config区0区长度", "该bit置1说明Boot_config区0区长度错误"),
            ("[3]检测Boot_config区0区校验结果", "该bit置1说明Boot_config区0区校验失败"),
            ("[4]检测Boot_config区1区BOOT模式", "该bit置1说明Boot_config区1区BOOT模式错误"),
            ("[5]检测Boot_config区1区PLATFORM_ID", "该bit置1说明Boot_config区1区PLATFORM_ID错误"),
            ("[6]检测Boot_config区1区长度", "该bit置1说明Boot_config区1区长度错误"),
            ("[7]检测Boot_config区1区校验结果", "该bit置1说明Boot_config区1区校验失败"),
            ("[24]检测厂商设备信息区CRC结果", "该bit置1说明厂商设备信息区CRC校验失败"),
            ("[25]检测描述符区Head CRC结果", "该bit置1说明描述符区Head CRC错误"),
            ("[26]检测描述符区PLATFORM_ID", "该bit置1说明描述符区PLATFORM_ID错误"),
            ("[27]检测描述符区使能位未使能", "该bit置1说明描述符区使能位未使能"),
            ("[28]描述符区数据CRC校验失败", "该bit置1说明描述符区数据CRC校验失败")
        });

        // BootFlag3[7:0]
        AddRegisterGroup("Boot阶段", "BootFlag3[7:0]", 8, new List<(string, string)>
        {
            ("Boot运行阶段", "Boot每经过一个阶段，都会对该寄存器赋不同的值")
        });

        // BootState[7:0]
        AddRegisterGroup("Boot阶段", "BootState[7:0]", 8, new List<(string, string)>
        {
            ("[0]Boot启动失败", "该bit置1说明Boot启动失败"),
            ("[1]描述符长度异常", "该bit置1说明描述符长度异常")
        });

        // McuResetNum[7:0]
        AddRegisterGroup("Boot阶段", "McuResetNum[7:0]", 8, new List<(string, string)>
        {
            ("[7:0]watchdog reset times", "记录ISP启动后，触发看门狗复位的次数")
        }, "0x80500284");

        // SoftWatchDog[7:0]
        AddRegisterGroup("Boot阶段", "SoftWatchDog[7:0]", 8, new List<(string, string)>
        {
            ("[7]1:starve", "该bit置1说明固件卡死")
        }, "只能直接读取硬件寄存器0x805002a4");

        // FlashState[7:0]
        AddRegisterGroup("Boot阶段", "FlashState[7:0]", 8, new List<(string, string)>
        {
            ("[0]1:检测flash是否存在", "该bit置1说明Flash不存在")
        });

        // Rtl_Mode_EN[31:0]
        AddRegisterGroup("Boot阶段", "Rtl_Mode_EN[31:0]", 32, new List<(string, string)>());

        // Firmware_Version[63:0]
        AddRegisterGroup("Boot阶段", "Firmware_Version[63:0]", 64, new List<(string, string)>());

        // USBDevicesStatus[7:0]
        AddRegisterGroup("Boot阶段", "USBDevicesStatus[7:0]", 8, new List<(string, string)>
        {
            ("1：reset after", ""),
            ("2：set address after", ""),
            ("3：set config after", "")
        });
        // SPI相关寄存器
        // ChipSPI_OverTime_Status[7:0]
        AddRegisterGroup("Boot阶段", "ChipSPI_OverTime_Status[7:0]", 8, new List<(string, string)> {
    ("2：busy status", "SPI为busy状态"),
    ("3：finished status", "SPI为finished状态")
});

        // Flash_OverTime_Status[7:0]
        AddRegisterGroup("Boot阶段", "Flash_OverTime_Status[7:0]", 8, new List<(string, string)> {
    ("[0]Flash忙碌状态", "Flash处于busy状态")
});

        // I2C_Busy_OverTime_Status[5:4]
        AddRegisterGroup("Boot阶段", "I2C_Busy_OverTime_Status[5:4]", 2, new List<(string, string)> {
    ("[0]busy状态", "I2C处于busy状态")
});

        // I2C_Finished_OverTime_Status[5:4]
        AddRegisterGroup("Boot阶段", "I2C_Finished_OverTime_Status[5:4]", 2, new List<(string, string)> {
    ("[0]busy状态", "I2C处于busy状态")
});

        // ChipSPI_OverTime_Cnt[15:0]
        AddRegisterGroup("Boot阶段", "ChipSPI_OverTime_Cnt[15:0]", 16, new List<(string, string)> {
    ("SPI超时计数", "等SPI状态超时次数")
});

        // Flash_OverTime_Cnt[15:0]
        AddRegisterGroup("Boot阶段", "Flash_OverTime_Cnt[15:0]", 16, new List<(string, string)> {
    ("Flash超时计数", "等Flash状态超时次数")
});

        // I2C_Finished_OverTime_Cnt[15:0]
        AddRegisterGroup("Boot阶段", "I2C_Finished_OverTime_Cnt[15:0]", 16, new List<(string, string)> {
    ("I2C结束超时计数", "等I2C结束状态超时次数")
});

        // I2C_Busy_OverTime_Cnt[15:0]
        AddRegisterGroup("Boot阶段", "I2C_Busy_OverTime_Cnt[15:0]", 16, new List<(string, string)> {
    ("I2C忙碌超时计数", "等I2C空闲状态超时次数")
});


        // resetverd1[10] - 数组
        AddArrayRegister("Boot阶段", "resetverd1[10]", 10, 32, "预留数组为32位数组");
    }

    /// <summary>
    /// 生成出图阶段寄存器信息
    /// </summary>
    private static void GenerateStreamRegisters()
    {
        // MipiRxState[7:0]
        AddRegisterGroup("出图阶段", "MipiRxState[7:0]", 8, new List<(string, string)>
        {
            ("[0] ECC single-bit error", "该bit置1说明ECC单bit错误"),
            ("[1] ECC multi-bit error", "该bit置1说明ECC多bit错误"),
            ("[2] CRC error", "该bit置1说明CRC错误"),
            ("[3] byte number error", "该bit置1说明字节数错误"),
            ("[4] Lane0 sot can't be found error", "该bit置1说明没有找到Lane0 sot"),
            ("[5] Lane1 sot can't be found error", "该bit置1说明没有找到Lane1 sot"),
            ("[6] Lane2 sot can't be found error", "该bit置1说明没有找到Lane2 sot"),
            ("[7] Lane3 sot can't be found error", "该bit置1说明没有找到Lane3 sot")
        });

        // IsStreamOn[7:0]
        AddRegisterGroup("出图阶段", "IsStreamOn[7:0]", 8, new List<(string, string)>
        {
            ("ISP开流标记位", "该字节置1说明ISP开始出图")
        });

        // IspSizeState[7:0]
        AddRegisterGroup("出图阶段", "IspSizeState[7:0]", 8, new List<(string, string)>
        {
            ("[0]isp mipi rx size error", "该bit置1说明isp mipi rx尺寸错误"),
            ("[1]isp crc input size error", "该bit置1说明isp crc input尺寸错误"),
            ("[2]isp output size error", "该bit置1说明isp output尺寸错误")
        });

        // IdcState[7:0]
        AddRegisterGroup("出图阶段", "IdcState[7:0]", 8, new List<(string, string)>
        {
            ("[0] idc_mux_afifo_full", "该bit置1说明idc_mux中接收mipirx的afifo full，当sensor mipi rx速率大于idcrt_clk频率时出现"),
            ("[1] idc_sram_overflow", "该bit置1说明idc中sram overflow，当sensor mipi rx一行的速率大于读出的速率"),
            ("[2] idc_afifo_full", "该bit置1说明idc中afifo full，当sensor mipi rx速率大于isp_clk频率时出现")
        });

        // JpegLengt[23:0]
        AddRegisterGroup("出图阶段", "JpegLengt[23:0]", 24, new List<(string, string)>
        {
            ("[15:0] Jpeg_Length", "Mjpeg模块处理的数据量大小")
        });

        // HostSetStreamFormat[7:0]
        AddRegisterGroup("出图阶段", "HostSetStreamFormat[7:0]", 8, new List<(string, string)>());

        // HostSetImageFormat[7:0]
        AddRegisterGroup("出图阶段", "HostSetImageFormat[7:0]", 8, new List<(string, string)>());


        // FrameEofCnt[7:0]
        AddRegisterGroup("出图阶段", "FrameEofCnt[7:0]", 8, new List<(string, string)>
    {
        ("记录idc开流后，usb开流前，错误帧的帧数", "idc开流后，usb开流前，有FrameEofCnt帧错误帧")
    });

        // StreamLoadFlag[7:0]
        AddRegisterGroup("出图阶段", "StreamLoadFlag[7:0]", 8, new List<(string, string)>
    {
        ("0：StreamInit", "开流初始化"),
        ("1：StreamOnRun", "USB开流"),
        ("2：StreamOverOnRun", "USB开流超时"),
        ("3：StreamLoadFinish", "加载拍照setting成功")
    });

        // USB_Stream_On_State[7:0]
        AddRegisterGroup("出图阶段", "USB_Stream_On_State[7:0]", 8, new List<(string, string)>
    {
        ("[0]USB开流前idc mux尺寸错误", "idc开流后，usb开流前idc mux尺寸错误"),
        ("[1]USB开流前idc top尺寸错误", "idc开流后，usb开流前idc top尺寸错误"),
        ("[2]USB开流前isp out尺寸错误", "idc开流后，usb开流前isp output尺寸错误")
    });



        // MipiRxSize[31:0]
        AddRegisterGroup("出图阶段", "MipiRxSize[31:0]", 32, new List<(string, string)>
        {
            ("[15:0] isp mipi rx vsize", "记录isp mipirx接收到的尺寸信息，即sensor输出尺寸"),
            ("[31:16] isp mipi rx hsize", "记录isp mipirx接收到的尺寸信息，即sensor输出尺寸")
        });

        // IdcMuxSize[31:0]
        AddRegisterGroup("出图阶段", "IdcMuxSize[31:0]", 32, new List<(string, string)>
        {
            ("[15:0] idc mux vsize", "记录idc mux接收到的尺寸信息"),
            ("[31:16] idc mux hsize", "记录idc mux接收到的尺寸信息")
        });

        // IdcTopSize[31:0]
        AddRegisterGroup("出图阶段", "IdcTopSize[31:0]", 32, new List<(string, string)>
        {
            ("[15:0] idc top vsize", "记录idc top接收到的尺寸信息"),
            ("[31:16] idc top hsize", "记录idc top接收到的尺寸信息")
        });

        // IspInputSize[31:0]
        AddRegisterGroup("出图阶段", "IspInputSize[31:0]", 32, new List<(string, string)>
        {
            ("[15:0] isp crc input vsize", "记录isp内部image path的输入尺寸信息"),
            ("[31:16] isp crc input hsize", "记录isp内部image path的输入尺寸信息")
        });

        // IspOutputSize[31:0]
        AddRegisterGroup("出图阶段", "IspOutputSize[31:0]", 32, new List<(string, string)>
        {
            ("[15:0] isp output vsize", "记录isp输出的图像尺寸信息"),
            ("[31:16] isp output hsize", "记录isp输出的图像尺寸信息")
        });

        // 各种尺寸寄存器
        AddSizeRegisters("出图阶段", "PreSize[31:0]", "");
        AddSizeRegisters("出图阶段", "LencSize[31:0]", "");
        AddSizeRegisters("出图阶段", "DpcSize[31:0]", "");
        AddSizeRegisters("出图阶段", "Nr3dSize[31:0]", "");
        AddSizeRegisters("出图阶段", "XcpbSize[31:0]", "");
        AddSizeRegisters("出图阶段", "YdeSize[31:0]", "");
        AddSizeRegisters("出图阶段", "YdnsSize[31:0]", "");

        // 窗口和缩放尺寸寄存器
        AddRegisterGroup("出图阶段", "Win0Size[31:0]", 32, new List<(string, string)>());
        AddRegisterGroup("出图阶段", "ScleSize[31:0]", 32, new List<(string, string)>());
        AddRegisterGroup("出图阶段", "Win1Size[31:0]", 32, new List<(string, string)>());
        AddRegisterGroup("出图阶段", "ModeSel0MaxSize[31:0]", 32, new List<(string, string)>());

        // FrameCnt[31:0]
        AddRegisterGroup("出图阶段", "FrameCnt[31:0]", 32, new List<(string, string)>
        {
            ("Frame Count", "记录当前出图的帧数")
        });

        // USB传输状态寄存器
        AddRegisterGroup("出图阶段", "USBTransState1[31:0]", 32, new List<(string, string)>
        {
            ("video_in_cnt[31:16]", ""),
            ("irq_udc_cnt[15:12]", ""),
            ("irq_enumon_cnt[11:8]", ""),
            ("irq_usb_cnt[7:4]", ""),
            ("irq_sta_cnt[3:0]", "")
        }, "0x8032016c");

        AddRegisterGroup("出图阶段", "USBTransState2[31:0]", 32, new List<(string, string)>
        {
            ("valid_chirp[10]", ""),
            ("dev_state[9:8]", ""),
            ("frm_trs_err_cnt[7:3]", ""),
            ("ad_pre_ram_full[1]", ""),
            ("ad_ram_full[0]", "")
        }, "(0x80320180)");

        AddRegisterGroup("出图阶段", "USBTransState3[31:0]", 32, new List<(string, string)>
        {
            ("[30:24]vd_pre_ram_full_cnt", "Usb buffer满了但没有溢出"),
            ("[22:16]vd_ram_full_cnt", "Usb buffer溢出"),
            ("[15:8]eof_err_cnt", ""),
            ("[7:0]sof_err_cnt", "")
        }, "(0x803201c8)");

        AddRegisterGroup("出图阶段", "USBTransState4[31:0]", 32, new List<(string, string)>
        {
            ("[31:0]img_length", "")
        }, "(0x803201cc)");

        // Setting状态寄存器
        AddRegisterGroup("出图阶段", "Setting2LoadStatus[31:0]", 32, new List<(string, string)>
        {
            ("[31:0]Setting2 load status", "记录Application中ISP和IQ生成函数的运行状态")
        });

        AddRegisterGroup("出图阶段", "Setting3LoadStatus[31:0]", 32, new List<(string, string)>
        {
            ("[31:0]Setting3 load status", "记录BootISP和IQ生成函数的运行状态")
        });

        // Host设置寄存器
        AddRegisterGroup("出图阶段", "HostSetStreamSize[31:0]", 32, new List<(string, string)>());
        AddRegisterGroup("出图阶段", "HostSetImageSize[31:0]", 32, new List<(string, string)>());
        AddRegisterGroup("出图阶段", "HostSetFrameRate[31:0]", 32, new List<(string, string)>());

        // resetverd1[10] - 数组
        AddArrayRegister("出图阶段", "resetverd1[10]", 10, 32, "预留数组为32位数组");
    }

    /// <summary>
    /// 生成Sensor阶段寄存器信息
    /// </summary>
    private static void GenerateSensorRegisters()
    {
        // SensorStreamState[7:0]
        AddRegisterGroup("Sensor阶段", "SensorStreamState[7:0]", 8, new List<(string, string)>
        {
            ("[0] 1:stream on 0:stream off", "该bit置1说明sensor流控开关已经打开，sensor可以正常输出数据流")
        });

        // SensorState[7:0]
        AddRegisterGroup("Sensor阶段", "SensorState[7:0]", 8, new List<(string, string)>
        {
            ("[0] 1:rear sensor iic error 0:rear sensor iic ok", "该bit置1说明后摄sensor IIC通讯异常"),
            ("[1] 1:rear sensor motor error 0:rear sensor motor ok", "该bit置1说明后摄sensor 马达通讯异常"),
            ("[2] 1:rear sensor EEPROM error 0:rear sensor EEPROM ok", "该bit置1说明后摄sensor EEPROM通讯异常"),
            ("[3] 1:front sensor iic error 0:rear sensor iic ok", "该bit置1说明前摄sensor IIC通讯异常"),
            ("[4] 1:front sensor EEPROM error 0:rear sensor EEPROM ok", "该bit置1说明前摄sensor EEPROM通讯异常")
        });

        // FrontSensorIndex[7:0]
        AddRegisterGroup("Sensor阶段", "FrontSensorIndex[7:0]", 8, new List<(string, string)>
        {
            ("3：SC820CS；4：GC08A8", "当前连接的前摄Index")
        });

        // RearSensorIndex[7:0]
        AddRegisterGroup("Sensor阶段", "RearSensorIndex[7:0]", 8, new List<(string, string)>
        {
            ("2：SC1320；1：GC13A0", "当前连接的后摄Index")
        });

        // SensorDetectState[7:0]
        AddRegisterGroup("Sensor阶段", "SensorDetectState[7:0]", 8, new List<(string, string)>
        {
            ("[0] 1:一号模组 detect error 0:一号模组 detect ok", "置一说明一号模组的厂商otp数据卡控失败"),
            ("[1] 1:二号模组 detect error 0:二号模组 detect ok", "置一说明二号模组的厂商otp数据卡控失败")
        });

        // RearSensorMotorMax[15:0]
        AddRegisterGroup("Sensor阶段", "RearSensorMotorMax[15:0]", 16, new List<(string, string)>
        {
            ("sensor motor DAC max data", "记录马达DAC最大值")
        });

        // RearSensorMotorMin[15:0]
        AddRegisterGroup("Sensor阶段", "RearSensorMotorMin[15:0]", 16, new List<(string, string)>
        {
            ("sensor motor DAC min data", "记录马达DAC最小值")
        });

        // resetverd1[10] - 数组
        AddArrayRegister("Sensor阶段", "resetverd1[10]", 10, 32, "预留数组为32位数组");
    }

    /// <summary>
    /// 生成主机交互寄存器信息
    /// </summary>
    private static void GenerateHostRegisters()
    {
        // 交互指令
        AddRegisterGroup("主机交互", "交互指令", 8, new List<(string, string)>());

        // resetverd1[10] - 数组
        AddArrayRegister("主机交互", "resetverd1[10]", 10, 32, "预留数组为32位数组");
    }



    /// <summary>
    /// 添加数组寄存器
    /// </summary>
    private static void AddArrayRegister(string category, string logInfo, int arraySize, int elementBitWidth, string description)
    {
        int elementRegisterCount = (elementBitWidth + 7) / 8;
        int totalRegisterCount = arraySize * elementRegisterCount;

        // 为数组的每个元素创建寄存器
        for (int i = 0; i < arraySize; i++)
        {
            for (int j = 0; j < elementRegisterCount; j++)
            {
                _allRegisters.Add(new RegisterInfo
                {
                    LogInfo = logInfo,
                    RegisterAddress = "", // 地址为空，后续自动计算
                    Parameter = $"[{i}] Element {j}",
                    Description = description,
                    Remark = "",
                    Category = category,
                    Abbreviation = GenerateAbbreviation(logInfo),
                    BitWidth = elementBitWidth,
                    RegisterCount = totalRegisterCount,
                    IsArray = true,
                    ArraySize = arraySize,
                    ArrayElementSize = elementRegisterCount
                });
            }
        }
    }

    /// <summary>
    /// 生成缩写
    /// </summary>
    private static string GenerateAbbreviation(string logInfo)
    {
        if (string.IsNullOrEmpty(logInfo)) return "";

        // 移除 [xx:xx] 和数组索引部分
        string cleanLogInfo = Regex.Replace(logInfo, @"\[.*?\]", "");

        // 提取首字母大写
        var words = cleanLogInfo.Split(new[] { ' ', '[', ']', ':', '-' }, StringSplitOptions.RemoveEmptyEntries);
        if (words.Length == 0) return "";

        if (words.Length == 1)
        {
            return words[0].Length <= 3 ? words[0].ToUpper() :
                   new string(words[0].Where(char.IsLetterOrDigit).Take(3).ToArray()).ToUpper();
        }

        // 多单词取首字母
        return new string(words.Select(w => char.IsLetterOrDigit(w[0]) ? char.ToUpper(w[0]) : ' ')
                              .Where(c => c != ' ')
                              .ToArray());
    }


    /// <summary>
    /// 添加寄存器组
    /// </summary>
    private static void AddRegisterGroup(string category, string logInfo, int bitWidth, List<(string Parameter, string Description)> parameters, string remark = "")
    {
        int registerCount = (bitWidth + 7) / 8; // 计算需要的寄存器数量

        foreach (var param in parameters)
        {
            _allRegisters.Add(new RegisterInfo
            {
                LogInfo = logInfo,
                RegisterAddress = "", // 地址为空，后续自动计算
                Parameter = param.Parameter,
                Description = param.Description,
                Remark = remark,
                Category = category,
                Abbreviation = GenerateAbbreviation(logInfo),
                BitWidth = bitWidth,
                RegisterCount = registerCount,
                IsArray = false,
                ArraySize = 0,
                ArrayElementSize = 0
            });
        }

        // 如果没有参数，添加一个空参数
        if (parameters.Count == 0)
        {
            _allRegisters.Add(new RegisterInfo
            {
                LogInfo = logInfo,
                RegisterAddress = "",
                Parameter = "",
                Description = "",
                Remark = remark,
                Category = category,
                Abbreviation = GenerateAbbreviation(logInfo),
                BitWidth = bitWidth,
                RegisterCount = registerCount,
                IsArray = false,
                ArraySize = 0,
                ArrayElementSize = 0
            });
        }
    }

    /// <summary>
    /// 添加尺寸寄存器组
    /// </summary>
    private static void AddSizeRegisters(string category, string logInfo, string description)
    {
        AddRegisterGroup(category, logInfo, 32, new List<(string, string)>
    {
        ("[15:0] vsize", "记录垂直尺寸信息"),
        ("[31:16] hsize", "记录水平尺寸信息")
    });
    }


}


/// <summary>
/// JSON数据序列化类
/// </summary>
public class RegisterInfoJsonData
{
    [JsonProperty("exportTime")]
    public string ExportTime { get; set; }

    [JsonProperty("totalRegisters")]
    public int TotalRegisters { get; set; }

    [JsonProperty("registers")]
    public List<RegisterInfo> Registers { get; set; }
}